package com.epam.javalab.giorgadze.task2.logic;

import com.epam.javalab.giorgadze.task2.entity.*;
import com.epam.javalab.giorgadze.task2.util.ConfiguratorManager;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class Parser implements TextParser {
    private static final Logger log = LoggerFactory.getLogger(Parser.class);
    private static final ConfiguratorManager configuratorManager = new ConfiguratorManager("regex.properties");

    @Override
    public Text parseTextToParagraphs(String string) {
        Text text = new Text();
        Pattern paragraphPattern = Pattern.compile(configuratorManager.getProperty("regex.paragraph"), Pattern.MULTILINE & Pattern.DOTALL);
        Matcher matcher = paragraphPattern.matcher(string);
        while (matcher.find()) {
            text.add(parseParagraphsToSentences(matcher.group()));
        }
        log.info("Text parsed to paragraphs");
        return text;
    }

    @Override
    public Paragraph parseParagraphsToSentences(String string) {
        Paragraph paragraph = new Paragraph();
        Pattern sentencePattern = Pattern.compile(configuratorManager.getProperty("regex.sentence"));
        Matcher matcher = sentencePattern.matcher(string);
        while (matcher.find()) {
            paragraph.add(parseSentenceToSentenceParts(matcher.group()));
        }
        log.info("Text parsed to sentences");
        return paragraph;
    }

    @Override
    public Sentence parseSentenceToSentenceParts(String string) {
        Sentence sentence = new Sentence();
        List<Symbol> list = parseWordsToSymbols(string).getSymbolList();
        Word word = new Word();
        for (Symbol symbol : list) {
            if (symbol.toString().equals(" ")||symbol.toString().equals(".")||symbol.toString().equals("?")
                    || symbol.toString().equals("!")) {
                sentence.add(word);
                sentence.add(symbol);
                word = new Word();
            } else {
                word.add(symbol);
            }
        }
        log.info("Text parsed to sentence parts");
        return sentence;
    }

    @Override
    public Word parseWordsToSymbols(String string) {
        Word word = new Word();
        Pattern symbolPattern = Pattern.compile(configuratorManager.getProperty("regex.symbol"), Pattern.DOTALL);
        Matcher matcher = symbolPattern.matcher(string);
        while (matcher.find()) {
            Symbol symbol = new Symbol(matcher.group());
            word.add(symbol);
        }
        log.info("Text parsed to symbols");
        return word;
    }

}
